﻿using System.Net.Mime;
using System.Reflection;
using System.Runtime.InteropServices;

namespace Printer;

public class BartenderExportToImage
{
    // 使用示例
    public static void TestExport()
    {
        string templateName = @"C:\Users\16893\Documents\BarTender\BarTender Documents\DP23.btw";
        string outputPath = @"C:\Users\16893\Documents\BarTender\BarTender Documents\label.png";
        // 确保输出目录存在
        ExportLabelToPng(templateName, outputPath);
    }
    
    public static void ExportLabelToPng(string templatePath, string outputPath)
    {
        dynamic btApp = null;
        dynamic btFormat = null;
        dynamic printSetup = null;

        try
        {
            // 创建 BarTender 应用程序实例
            btApp = Activator.CreateInstance(Type.GetTypeFromProgID("BarTender.Application"));
            btApp.Visible = false;
        
            // 打开标签文件
            btFormat = btApp.Formats.Open(templatePath, false, "");
        
            // 设置标签变量
            // btFormat.SetNamedSubStringValue("Field002", "wander");
            btFormat.ExportToImage(outputPath);
         
        
            Console.WriteLine($"标签成功导出到: {outputPath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"导出失败: {ex.Message}");
            throw; // 可以选择重新抛出异常或处理
        }
        finally
        {
            // 清理资源
            if (printSetup != null)
            {
                try
                {
                    Marshal.ReleaseComObject(printSetup);
                }
                catch { }
            }
        
            if (btFormat != null)
            {
                try
                {
                    btFormat.Close(0); // 0 = btDoNotSaveChanges
                    Marshal.ReleaseComObject(btFormat);
                }
                catch { }
            }
        
            if (btApp != null)
            {
                try
                {
                    btApp.Quit(0); // 0 = btDoNotSaveChanges
                    Marshal.ReleaseComObject(btApp);
                }
                catch { }
            }
        }
    }
    

  
}